package cn.jdy.plugins.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.anquan.entity.CompanySafe;
import cn.jdy.anquan.service.CompanySafeService;
import cn.jdy.common.constant.BankConstant;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.ScoreRuleUtil;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.SpringUploadFile;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.payment.entity.Orders;
import cn.jdy.payment.service.OrderService;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Business;
import cn.jdy.plugins.entity.Discuss;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.BusinessService;
import cn.jdy.plugins.service.CollectService;
import cn.jdy.plugins.service.DiscussService;

/**
 * 用户中心
 *
 * @author zhaigt
 */
@Controller
@RequestMapping("/member")
public class MemberCtrl extends BaseCtrl {
  @Autowired
  private CollectService collectService;
  @Autowired
  private OrderService orderService;
  @Autowired
  private BusinessService businessService;
  @Autowired
  private ConfService confService;
  @Autowired
  private DiscussService discussService;
  @Autowired
  private CompanySafeService companySafeService;

  /**
   * 会员 资料管理
   *
   * @return /s9/vip/myInfo.jsp
   * @description: 会员管理 资料管理
   * @author: wuzhiliang
   * @date: 2013-10-15 16:53
   */
  @RequestMapping("/myInfo")
  public ModelAndView myInfo(Orders order) {
    ModelAndView mv = new ModelAndView("/my/my.jsp");
    try {
      mv.addObject("msg", request.getParameter("msg"));
      // 用户信息 手机号中间替换为*
      Member member = super.getMember(true);
      // 拼接最终值
      String mobile = member.getMobile();
      if(!StringUtil.isNullOrEmpty(mobile)) {
        mobile = mobile.substring(0, 3) + "*****" + mobile.substring(mobile.length() - 3, mobile.length());
        mv.addObject("mobile", mobile);
      }
      /* 等级计算 等级类型分2种3级 */
      Integer score = member.getScore();
      if(score==null) score = 0;
      int createrlevel = ScoreRuleUtil.getlevel(score);
      mv.addObject("createrlevel", String.valueOf(createrlevel));
      mv.addObject("member", member);

      // 收藏总商机记录数
      mv.addObject("collectCount", collectService.count(member.getId(), null));
      // 下载总商机记录数
      long orderCount = orderService.count("userId", member.getId(),"status", BankConstant.ORDER_SUC);
      mv.addObject("orderCount", orderCount);
      // 上传总商机记录数
      Business busbo = new Business();
      busbo.setCreater(member.getId());
//      busbo.setStatus("1");
      Long busCount = businessService.count(busbo);
      mv.addObject("upsjCount", busCount);

      
      
      //设置分页信息
      if(order.getiDisplayLength() == 0) order.setiDisplayLength(5);                //默认长度5
      if(order.getPageNo()<=0) order.setPageNo(1);                                  //默认页数1
      order.setiDisplayStart((order.getPageNo() - 1) * order.getiDisplayLength());  //显示起始索引

      order.setUserId(getMember(false).getId());

      mv.addObject("dataList", orderService.queryOrders(order, null, null));
      mv.addObject("total", orderService.count(order, null, null));
      mv.addObject("pageNo", order.getPageNo());
      
      
    } catch(Exception e) {
      mv.addObject("msg", "error");
      BaseLog.e(this.getClass(), "updResetPwd:会员 资料管理有误", e);
    }
    return mv;
  }

  @RequestMapping(value = "/forUpload")
  public ModelAndView forUpload(DefaultMultipartHttpServletRequest request) {
    ModelAndView mv = new ModelAndView("/upfileImg.jsp");
    String savePath = "userFora";
    try {
      Map<String, String> reMap = SpringUploadFile.upload(request, savePath);
      if(StringUtil.isNullOrEmpty(reMap.get("errorInfo"))) {
        mv.addObject("newUrl", reMap.get("newUrl"));
      } else {
        mv.addObject("errorInfo", reMap.get("errorInfo"));
      }
    } catch(BaseException e) {
      BaseLog.e(this.getClass(), "会员 头像预览失败", e);
    }
    return mv;
  }

  /**
   * 会员头像修改
   *
   * @param imgUrl
   * @return
   */
  @RequestMapping("/forUpdateForeImg")
  @ResponseBody
  public Map<String, Object> forUpdateForeImg(String imgUrl) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      if(!StringUtil.isEmpty(imgUrl)) {
        Member memberBo = (Member) super.getMember();
        memberBo.setPhoto(imgUrl);
        memberService.updateForeImg(memberBo);
      }
      jsonMap.put("msg", "success");
    } catch(BaseException e) {
      jsonMap.put("msg", "error");
      BaseLog.e(this.getClass(), "updResetPwd:会员头像修改有误", e);
    }

    return jsonMap;
  }

  /**
   * 会员管理手机号重置
   *
   * @param mobile
   * @param userid
   * @return
   */
  @RequestMapping("/forUpdateMobile")
  public ModelAndView forUpdateMobile(String mobile, String userid) {
    ModelAndView mv = new ModelAndView("/member/myInfo");
    try {
      Member mbo = new Member();
      mbo.setMobile(mobile);
      mbo.setId(userid);
      memberService.updateMobile(mbo);

      Member memberBo = (Member) super.getMember();
      memberBo.setMobile(mobile);
      mv.addObject("msg", "success");
    } catch(BaseException e) {
      mv.addObject("msg", "error");
      BaseLog.e(this.getClass(), "updResetPwd:会员管理手机号重置有误", e);
    }
    return mv;
  }

  /**
   * 会员管理用手机号重置密码
   *
   * @return
   */
  @RequestMapping("/forUpdatePwd")
  public ModelAndView forUpdatePwd(String password) {
    ModelAndView mv = new ModelAndView("redirect:/login?errorType=10");
    try {
      Member mbo = new Member();
      Member memberBo = super.getMember();
      mbo.setId(memberBo.getId());
      mbo.setPassword(SafeUtil.md5(password).substring(8, 16));
      memberService.updResetPwd(mbo);
      session.invalidate();
    } catch(BaseException e) {
      BaseLog.e(this.getClass(), "updResetPwd:密码修改有误", e);
    }
    return mv;
  }
  
  

  /**
   * 我的贡献信息
   *
   * @param business
   * @return
   */
  @RequestMapping("/forMygongxian")
  public ModelAndView forMygongxian(Business business) {
    ModelAndView mv = new ModelAndView("/my/mygongxian.jsp");
    try {
      if(business.getiDisplayLength() == 0) business.setiDisplayLength(5);                //默认长度5
      if(business.getPageNo()<=0) business.setPageNo(1);                                  //默认页数1
      business.setiDisplayStart((business.getPageNo() - 1) * business.getiDisplayLength());  //显示起始索引

      business.setCreater(getMember().getId());

      mv.addObject("dataList", businessService.query(business));
      mv.addObject("total", businessService.count(business));
      mv.addObject("pageNo", business.getPageNo());
      mv.addObject("size", business.getiDisplayLength());
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "查询我的贡献信息错误", e);
    }
    return mv;
  }

  /**
   * 查看我的贡献消息详情 查询评论
   * @param discuss
   * @return
   */
  @RequestMapping("/queryDis")
  @ResponseBody
  public List<Discuss> queryDis(Discuss discuss) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {
      return discussService.find("businessId", discuss.getBusinessId());
    } catch(Exception e) {
      jsonMap.put("statusCode", 500);
      BaseLog.e(this.getClass(), "查询评论错误", e);
    }
    return null;
  }
  
  /**
   * @param bo
   * @return
   * @title : 上传我的加盟信息
   * @description: 跳转到上传我的加盟信息页面
   */
  @RequestMapping("/forMyupsjfile")
  public ModelAndView forMyupsjfile(Business bo) {
    ModelAndView mv = new ModelAndView("/my/myupsjfile.jsp");
    try {
      List<ConfValue> businessclassList = confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L);// 商分类
      // 8
      // 放常量
      mv.addObject("classList", businessclassList);
      // 预计加盟时间
      Date date1 = new Date();
      mv.addObject("addYear", date1.getYear()+1900);// 当前年份
      mv.addObject("addMonth", date1.getMonth()+1);// 当前月份
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "跳转到上传我的加盟信息页面错误", e);
    }
    return mv;
  }

  @RequestMapping("/checkPwd")
  @ResponseBody
  public Map<String, Object> checkPwd(String param) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    Member member = super.getMember();
    if(param!=null && member!=null && SafeUtil.md5(param).substring(8, 16).equals(member.getPassword())) {
      jsonMap.put("status", "y");
    } else {
      jsonMap.put("status", "n");
      jsonMap.put("info", "原密码错误");
    }
    return jsonMap;
  }
  
  /**
   * 用户中心 - 我的网站安全
   *
   * @return
   */
  @RequestMapping("/mysafe")
  public ModelAndView safe() {
    ModelAndView mv = new ModelAndView("/my/myCompanySafe.jsp");
    try {
      mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "中小企业资料库-- 网站名片", e);
    }
    return mv;
  }
  
  /**
   * 用户中心 - 我的网站安全
   *
   * @return
   */
  @RequestMapping("/savesafe")
  public ModelAndView savesafe(CompanySafe entity) {
    ModelAndView mv = new ModelAndView("/my/myCompanySafe.jsp");
    Member mbo = (Member) session.getAttribute("user");
    if(mbo == null){
      mv.setViewName("404.jsp");
    }else{
      try {
        Integer companyId = mbo.getCompany().getId();
        entity.setCompanyId(companyId);
        entity.setCreateTime(DateUtil.getCurrentDate2());
        companySafeService.save(entity);
        mv.addObject("status", "200");
        mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_BUSINESS, 0L));
      } catch(Exception e) {
        mv.addObject("status", "500");
        BaseLog.e(this.getClass(), "中小企业资料库-- 网站名片", e);
      }
    }
    return mv;
  }
}